//
//  PinterestCoordinator.swift
//  SwiftUILean
//
//  Created by wyknmjj on 2024/5/14.
//

import SwiftUI


@Observable
class PinterestCoordinator{
    var _result=initResult([] as [PinterestItem])    
    var isLoading:Bool {
        return _result.version != _result.data.version
    }
    var result: PromiseResult<[PinterestItem]>{
        return _result.data.data
    }
    
    func reload(){
        Task{
            await reduceResult(getSamplePinterestItems) {
                return _result
            } setValue: { v in
                _result=v
            }
        }
    }
    
    init(){
        reload()
    }
    
    
    var scrollView: UIScrollView = .init(frame:.zero)
    
    var rect:CGRect = .zero
    var animationLayer:UIImage?
    
    var animateView = false
    var hideLayer = false
    var hideRootView = false
    
    func createVisibleAreaShapshot(){
        //取scrollView的可见部分而不是全部
        let renderer = UIGraphicsImageRenderer(size: scrollView.bounds.size)
        let image = renderer.image { ctx in
            ctx.cgContext.translateBy(x: -scrollView.contentOffset.x, y: -scrollView.contentOffset.y)
            scrollView.layer.render(in: ctx.cgContext)
        }
        animationLayer = image
    }
    
    var selectedItem: PinterestItem?
    
    var headerOffset:CGFloat = 0
    
    
    
    func toggleView(show: Bool,frame: CGRect, post: PinterestItem){
        if show {
            selectedItem = post
            rect = frame
            
            createVisibleAreaShapshot()
            
            hideRootView = true
            
            withAnimation(.easeInOut(duration: 0.3),completionCriteria: .removed) {
                animateView = true
            } completion: {
                self.hideLayer = true
            }
        }else{
            hideLayer = false
            withAnimation(.easeInOut(duration: 0.3),completionCriteria: .removed){
                animateView = false
            }completion: {
                DispatchQueue.main.async{
                    self.resetAnimationProperties()
                }
            }
        }
    }
    
    func resetAnimationProperties(){
        headerOffset = 0
//        rect = .zero
        selectedItem = nil
        animationLayer = nil
        hideRootView = false
    }
}

/**
 从SwiftUI的ScrollView里提取UIKit ScrollView
 */
struct ScrollViewExtractor: UIViewRepresentable{
    var result: (UIScrollView) -> ()
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        view.backgroundColor = .clear
        view.isUserInteractionEnabled = false
        DispatchQueue.main.async {
            if let scrollView = view.superview?.superview?.superview as? UIScrollView {
                result(scrollView)
            }
        }
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context){
        
    }
}
